//
//  FSCMessageController.swift
//  FamiliesSchoolConnection
//
//  Created by 花花蔡 on 2016/12/22.
//  Copyright © 2016年 com.HuaHuaCai. All rights reserved.
//

import UIKit
import MJRefresh

class FSCMessageController: UITableViewController {
    
    //使用列表视图模型加载数据
    fileprivate var messageListVM = FSCMessageListViewModel()
    //回复内容输入框属性
    fileprivate var inputTextF:UITextField?
    //输入宽工具条属性
    fileprivate var replayInputToolBar:UIView?
    //纪录点击了回复按钮对应的cell
    fileprivate var currentCell = JXMessageCell()
    
    
//MARK:视图生命周期

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tableView.mj_header.beginRefreshing()

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.register(UINib.init(nibName: "JXMessageCell", bundle: nil), forCellReuseIdentifier: "messageCell")
        
        tableView.estimatedRowHeight = 350
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .none
        //添加右上角发布按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "release_msg", target: self, action: #selector(releaseInfoBtnClicked))
        
        //注册通知监听键盘弹出
        NotificationCenter.default.addObserver(self, selector: #selector(keybordNotifacation(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //添加下拉刷新控件
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.downLoadData(refreshType: .down)
        })
        
        //添加上拉加载更多
        tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { [weak self] in
            self?.downLoadData(refreshType: .up)
        })
    }
    
    //设置回复输入工具条
    func setupReplayInputToolBar() -> Void {
        //创建输入工具条
        replayInputToolBar = UIView(frame: CGRect(x: 0, y: screenHeight, width: screenWidth, height: 44))
        replayInputToolBar?.backgroundColor = UIColor.colorWithHex(hexColor: grayColor)
        //创建文本输入框
        inputTextF = UITextField(frame: CGRect(x: 8, y: 2, width: screenWidth - 8 - 44, height: 40))
        inputTextF?.placeholder = "回复就是一种鼓励"
        inputTextF?.borderStyle = .roundedRect
        replayInputToolBar?.addSubview(inputTextF!)
        
        //确定按钮
        let sureBtn = UIButton(type: .system)
        sureBtn.frame = CGRect(x: screenWidth - 44, y: 0, width: 44, height: 44)
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(UIColor.colorWithHex(hexColor: blueColor), for: .normal)
        sureBtn.addTarget(self, action: #selector(replaySureBtnClicked), for: .touchUpInside)
        replayInputToolBar?.addSubview(sureBtn)
        
        //添加在窗口视图上面
        UIApplication.shared.keyWindow?.addSubview(replayInputToolBar!)
    
    }
    
    
    
    //加载数据
    func downLoadData(refreshType:LoadType) -> Void {
        
        messageListVM.loadData(refreshType: refreshType) { [weak self](isRefresh) in
            if isRefresh {
                self?.tableView.reloadData()
            }
            //结束下拉刷新
            if refreshType == .down {
                self?.tableView.mj_header.endRefreshing()
            }else {
                self?.tableView.mj_footer.endRefreshing()
            }
            
        }
        
    }
    
    //发布按钮的回调方法
    func releaseInfoBtnClicked() -> Void {
        if inputTextF != nil {
            endKeybord()
        }
        navigationController?.pushViewController(HSReleaseInfoController(), animated: true)
    }
    
    
}



// MARK: - Table view data source and delegate

extension FSCMessageController {
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return messageListVM.messageModelArr.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! JXMessageCell
        cell.selectionStyle = .none
        let modelVM = messageListVM.messageModelArr[indexPath.row ]
        cell.messageVM = modelVM
        
        cell.likeBtnBlock = { [weak self] (clickCell) in
            self?.likeBtnClicked(cell:clickCell)

        }
        
        cell.replayBtnBlock = { [weak self] (clickCell) in
            self?.replayBtnClicked(cell: clickCell)

        }
        
        return cell
    }
    
    //拖动表格视图的代理方法
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == tableView {
            endKeybord()
        }
    }
    
}

//MARK:点赞和回复相关功能实现代码
extension FSCMessageController {
    
    //1.回复功能
    func replayBtnClicked(cell:JXMessageCell) -> Void {
       
        //纪录当前cell用于通知回调方法中计算cell的位置
        currentCell = cell

        //当点击回复按钮时才添加输入工具条
        if replayInputToolBar == nil || replayInputToolBar?.superview == nil {
            setupReplayInputToolBar()
        }
        
        //设置文本输入框为第一响应者
        inputTextF?.becomeFirstResponder()
       
    }
    
    //1.1 回复内容确定按钮的监听回调事件方法
    func replaySureBtnClicked() -> Void {
        
        endKeybord()
        
        //获得cell对应的视图模型
        guard let messageVM = currentCell.messageVM else {
            return
        }
        // 获得回复接口
        let replayUrl = "ZH-schoolname-S-submitJXReplay"
        //获得通知ID
        let notify_ID = messageVM.message.not_id
        //获得输出的内容
        guard let replayContent = inputTextF?.text, inputTextF?.text != "" else {
            HSAlertView.bottomAlertView("回复内容不能为空")
            return
        }
        let parm = ["key":userID,"id":notify_ID,"content":replayContent,"user_type":2] as [String : Any]
        
        FSCNetworkTools.shared.request(url: replayUrl, parameters: parm) { (success, failed) in
            guard let success = success as? NSDictionary, let dictArray = success["data"] as? [[String:Any]] else {
                HSAlertView.bottomAlertView("回复数据加载异常")
                return
            }
            
            //创建一个保存回复模型的数组
            var replayModels = [FSCReplayListModel]()
            for dict in dictArray {
                //初始化模型
                let model = FSCReplayListModel(dict: dict)
                replayModels.append(model)
            }
            //获得当前消息模型
            let newMessage = messageVM.message
            newMessage.replaylist = replayModels
            //重新赋值触发富文本属性设置
            messageVM.message = newMessage
            
            self.tableView.reloadData()
        }
        
    }
    
    //1.2 键盘监听通知的回调方法
    func keybordNotifacation(notify:Notification) -> Void {
        //获得键盘对应的frame
        let keybordFrame = notify.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect
        //获得键盘的y值
        let keybordY = keybordFrame?.minY ?? 0.0
        //根据键盘位置设置输入工具条位置
        replayInputToolBar?.center = CGPoint(x: screenWidth/2, y: keybordY - 22)
        //如果当前键盘隐藏就移除工具条
        if keybordY == screenHeight {
            replayInputToolBar?.removeFromSuperview()
            //replayInputToolBar = nil
            }
        //设置表格视图自动设备键盘高度
        //获得窗口视图                 
        guard let keyWindow = UIApplication.shared.keyWindow else {
                return
        }
        
        //获得cell对应窗口的frame
        let rect = keyWindow.convert(currentCell.frame, from: tableView)
        
        //获得cell的偏移量
        let offset = rect.maxY - (keybordY - 44)
        if offset <= 0 {
            return
        }
        //获得表格视图当前的偏移量
        let currentOffsetY = tableView.contentOffset.y
        //重新设置表格视图的偏移量
        let newOffsetP = CGPoint(x: 0, y: currentOffsetY + offset)
        tableView.setContentOffset(newOffsetP, animated: true)
        
    }
    
    //2.点赞功能
    func likeBtnClicked(cell:JXMessageCell) -> Void {
        
        currentCell = cell

        guard let messageVM = currentCell.messageVM,let studentName = userInfo["studentName"] as? String else {
            return
        }
       
        let likeList = messageVM.message.likelist
        
        if ((likeList?.range(of: studentName)) != nil)  {
            HSAlertView.bottomAlertView("已经点赞过了")
            return
        }

        
        let urlStr = "ZH-schoolname-S-submitJXLike"
        let not_ID = messageVM.message.not_id
        let parm = ["key":userID,"id":not_ID,"user_type":2] as [String : Any]
        
        FSCNetworkTools.shared.request(url: urlStr, parameters: parm) { (data, error) in
            
            guard let data = data as? NSDictionary, let dictArr = data["data"] as? [[String:Any]] else {
                HSAlertView.bottomAlertView("加载异常")
                return
            }
            
            let newMessage = messageVM.message

            for dict in dictArr {
                newMessage.likenum = dict["likenum"] as! Int
                newMessage.likelist = dict["likelist"] as! String?
                messageVM.message = newMessage
            }
            self.tableView.reloadData()
        }
        
    }
    
    func endKeybord() -> Void {
        //退出键盘
        inputTextF?.resignFirstResponder()
        
    }
}



